import { Enums, getRenderingEngine, Settings } from "@cornerstonejs/core";
import * as cornerstoneTools from "@cornerstonejs/tools";
import { renderingEngineId2d } from "../cornerstone3D";
// import ZoomMouseWheelTool from "@/cornerstone3D/ZoomMouseWheelTool";
import MyProbeTool from "./MyProbeTool";
import CTRTool from "./CTRTool";

const {
	ToolGroupManager,
	Enums: csToolsEnums,
	CrosshairsTool,
	TrackballRotateTool,
	StackScrollTool,
	WindowLevelTool,
	PanTool,
	ZoomTool,
	ScaleOverlayTool,
	ProbeTool,
	LengthTool,
	AngleTool,
	RectangleROITool,
	EllipticalROITool,
	PlanarFreehandROITool,
	CobbAngleTool,
	ArrowAnnotateTool,
	LabelTool,
	EraserTool,
	OrientationMarkerTool,
	PlanarRotateTool,
	ReferenceLinesTool,
	OverlayGridTool,
	annotation,
	drawing,
	utilities,
	synchronizers,
	SynchronizerManager
} = cornerstoneTools;

const { filterViewportsWithToolEnabled } = utilities.viewportFilters;

// let { drawHandles } = drawing;
const { MouseBindings, KeyboardBindings } = csToolsEnums;
const { createImageSliceSynchronizer } = synchronizers;
const { getAnnotations, removeAnnotation, removeAnnotations, removeAllAnnotations } =
	annotation.state;

const toolGroupId = "tpid_2d";
const toolGroup = ToolGroupManager.createToolGroup(toolGroupId);
const imageSliceSync = "IMAGE_SLICE_SYNCHRONIZER_ID";

let selectedToolName = "MyProbe";

// const vrToolGroupId = "tpid_vr";
// const vrToolGroup = ToolGroupManager.createToolGroup(vrToolGroupId);

const measureTools = [
	{
		label: "无测量",
		value: WindowLevelTool.toolName
	},
	{
		label: "点",
		value: ProbeTool.toolName
	},
	{
		label: "点-自定义",
		value: MyProbeTool.toolName
	},
	{
		label: "直线",
		value: LengthTool.toolName
	},
	{
		label: "角度",
		value: AngleTool.toolName
	},
	{
		label: "矩形",
		value: RectangleROITool.toolName
	},
	{
		label: "椭圆",
		value: EllipticalROITool.toolName
	},
	{
		label: "曲线",
		value: PlanarFreehandROITool.toolName
	},
	{
		label: "Cobb角度",
		value: CobbAngleTool.toolName
	},
	{
		label: "箭头",
		value: ArrowAnnotateTool.toolName
	},
	{
		label: "标签",
		value: LabelTool.toolName
	},
	{
		label: "删除",
		value: EraserTool.toolName
	}
];

function initTools() {
	cornerstoneTools.addTool(CrosshairsTool);
	cornerstoneTools.addTool(TrackballRotateTool);
	cornerstoneTools.addTool(OrientationMarkerTool);
	// cornerstoneTools.addTool(ZoomMouseWheelTool);

	// 标尺
	// cornerstoneTools.addTool(ScaleOverlayTool);

	// 参考线
	cornerstoneTools.addTool(ReferenceLinesTool);
	// cornerstoneTools.addTool(OverlayGridTool);

	// 操作
	cornerstoneTools.addTool(WindowLevelTool);
	cornerstoneTools.addTool(PanTool);
	cornerstoneTools.addTool(ZoomTool);
	cornerstoneTools.addTool(StackScrollTool);

	// 旋转
	cornerstoneTools.addTool(PlanarRotateTool);

	// 测量工具
	cornerstoneTools.addTool(ProbeTool);
	cornerstoneTools.addTool(MyProbeTool);
	cornerstoneTools.addTool(LengthTool);
	cornerstoneTools.addTool(AngleTool);
	cornerstoneTools.addTool(RectangleROITool);
	cornerstoneTools.addTool(EllipticalROITool);
	cornerstoneTools.addTool(PlanarFreehandROITool);
	cornerstoneTools.addTool(CTRTool);
	cornerstoneTools.addTool(CobbAngleTool);
	cornerstoneTools.addTool(ArrowAnnotateTool);
	cornerstoneTools.addTool(LabelTool);
	cornerstoneTools.addTool(EraserTool);

	// Add tools to the tool group

	toolGroup.addTool(WindowLevelTool.toolName);
	toolGroup.addTool(PanTool.toolName);
	toolGroup.addTool(ZoomTool.toolName, {
		zoomToCenter: true,
		invert: false, // 修复缩放方向：false表示手指伸开为放大
		minZoomScale: 0.1,
		maxZoomScale: 20
	});
	toolGroup.addTool(StackScrollTool.toolName);

	// toolGroup.addTool(ScaleOverlayTool.toolName);
	toolGroup.addTool(PlanarRotateTool.toolName);

	toolGroup.addTool(ProbeTool.toolName, {
		handleRadius: "4"
	});

	toolGroup.addTool(MyProbeTool.toolName, {
		handleRadius: "4"
	});

	toolGroup.addTool(LengthTool.toolName);
	toolGroup.addTool(AngleTool.toolName);
	toolGroup.addTool(RectangleROITool.toolName);
	toolGroup.addTool(EllipticalROITool.toolName);
	toolGroup.addTool(PlanarFreehandROITool.toolName);
	toolGroup.addTool(CTRTool.toolName, {
		showLinesText: true
	});
	toolGroup.addTool(CobbAngleTool.toolName, {
		showArcLines: false
	});
	toolGroup.addTool(ArrowAnnotateTool.toolName);
	toolGroup.addTool(LabelTool.toolName);

	// toolGroup.setToolConfiguration(
	// 	LabelTool.toolName,
	// 	{
	// 		getTextCallback: fn => {
	// 			// console.log("getTextCallback", fn);
	// 			return fn("L");
	// 		},
	// 		changeTextCallback: (a, b, fn) => {
	// 			return fn("L");
	// 		}
	// 	},
	// 	true
	// );

	// toolGroup.addTool(LabelTool.toolName);
	toolGroup.addTool(EraserTool.toolName);

	// 参考线
	toolGroup.addTool(ReferenceLinesTool.toolName, {
		sourceViewportId: ""
	});

	// toolGroup.addTool(OverlayGridTool.toolName, {
	// 	sourceImageIds: []
	// });

	toolGroup.setToolEnabled(ReferenceLinesTool.toolName);
	// toolGroup.setToolDisabled(ReferenceLinesTool.toolName);

	// toolGroup.setToolEnabled(OverlayGridTool.toolName);

	// 窗口调窗工具不默认激活，避免与测量工具冲突
	toolGroup.setToolPassive(WindowLevelTool.toolName);
	toolGroup.setToolActive(PanTool.toolName, {
		bindings: [
			{
				mouseButton: MouseBindings.Auxiliary // Middle Click
			}
		]
	});
	toolGroup.setToolActive(ZoomTool.toolName, {
		bindings: [
			{
				mouseButton: MouseBindings.Secondary // Right Click
			}
		]
	});
	toolGroup.setToolActive(StackScrollTool.toolName, {
		bindings: [
			{
				mouseButton: MouseBindings.Wheel // Wheel Mouse
			}
		]
	});

	toolGroup.setToolActive(PlanarRotateTool.toolName, {
		bindings: [
			{
				mouseButton: MouseBindings.Wheel, // Shift Wheel Mouse
				modifierKey: KeyboardBindings.Shift
			}
		]
	});

	// Create synchronizers
	createImageSliceSynchronizer(imageSliceSync);

	// toolGroup.setToolConfiguration(
	// 	ScaleOverlayTool.toolName,
	// 	{
	// 		scaleLocation: "right"
	// 	},
	// 	true //overwrite
	// );

	// toolGroup.setToolEnabled(ScaleOverlayTool.toolName);

	// console.log("initTools getDefaultSettings", Settings.getDefaultSettings());
	// Settings.getDefaultSettings().set("useCursors", false);
	annotation.config.style.setToolGroupToolStyles(toolGroupId, {
		[LabelTool.toolName]: { textBoxFontSize: "28px" }
	});
	// annotation.config.style.setToolGroupToolStyles(toolGroupId, {
	// 	// 修改LabelTool字体
	// 	[LabelTool.toolName]: { textBoxFontSize: "28px" },
	// 	// 修改LengthTool字体
	// 	[LengthTool.toolName]: { textBoxFontSize: "20px" },
	// 	// 修改toolGroup中所有Tool字体
	// 	global: { textBoxFontSize: "12px" }
	// });
}

function setVieportToolStyles(viewportId) {
	annotation.config.style.setViewportToolStyles(viewportId, {
		// 修改LabelTool字体
		[LabelTool.toolName]: { textBoxFontSize: "60px" },
		// 修改viewport中所有Tool字体
		global: { textBoxFontSize: "8px" }
	});
}

function activeMeasureTool(toolName) {
	console.log("activeMeasureTool被调用，工具名称:", toolName);
	console.log("当前选中的工具:", selectedToolName);

	try {
		// 检查工具是否存在于工具组中
		const hasTool = toolGroup.hasTool(toolName);
		console.log("工具是否存在:", toolName, hasTool);

		if (!hasTool) {
			console.error("工具不存在于工具组中:", toolName);
			return;
		}

		// 检查工具是否已启用
		const isToolEnabled = toolGroup.getToolInstance(toolName);
		console.log("工具实例:", isToolEnabled);

		// 先设置旧工具为被动状态
		if (selectedToolName && selectedToolName !== toolName) {
			toolGroup.setToolPassive(selectedToolName);
			console.log("旧工具设置为被动:", selectedToolName);
		}

		// 确保窗口调窗工具被完全禁用 - 更彻底的解决方案
		// 先禁用工具
		toolGroup.setToolDisabled(WindowLevelTool.toolName);

		// 再设置为被动状态
		toolGroup.setToolPassive(WindowLevelTool.toolName);

		// 清除所有绑定配置
		toolGroup.setToolConfiguration(
			WindowLevelTool.toolName,
			{
				bindings: []
			},
			true
		); // 强制覆盖

		// 检查禁用是否生效
		const disabledOptions = toolGroup.getToolOptions(WindowLevelTool.toolName);
		console.log("禁用后窗口调窗工具状态:", JSON.stringify(disabledOptions, null, 2));

		// 如果仍然处于激活状态，强制设置为被动
		if (disabledOptions && disabledOptions.mode === "Active") {
			console.log("窗口调窗工具仍然处于激活状态，强制设置为被动");
			toolGroup.setToolPassive(WindowLevelTool.toolName);
			toolGroup.setToolDisabled(WindowLevelTool.toolName);
		}

		console.log("窗口调窗工具已完全禁用");

		// 同时确保其他基本工具不会干扰测量工具
		// 将缩放、移动、滚动工具设置为被动状态，但保持它们的绑定
		toolGroup.setToolPassive(ZoomTool.toolName);
		toolGroup.setToolPassive(PanTool.toolName);
		toolGroup.setToolPassive(StackScrollTool.toolName);

		console.log("基本工具已设置为被动状态");

		// Set the new tool active
		toolGroup.setToolActive(toolName, {
			bindings: [
				{
					mouseButton: MouseBindings.Primary // Left Click
				}
			]
		});

		console.log("工具激活成功:", toolName);

		// Set the new tool as the selected tool
		selectedToolName = toolName;
		console.log("新工具设置为选中:", selectedToolName);

		// 再次确认窗口调窗工具状态
		const finalWindowToolOptions = toolGroup.getToolOptions(WindowLevelTool.toolName);
		console.log(
			"最终窗口调窗工具状态:",
			JSON.stringify(finalWindowToolOptions, null, 2)
		);

		// 强制刷新鼠标光标 - 通过触发虚拟鼠标移动事件
		console.log("尝试强制刷新鼠标光标");
		try {
			// 获取当前活动的viewport
			const renderingEngine = getRenderingEngine(renderingEngineId2d);
			if (renderingEngine) {
				const viewports = renderingEngine.getViewports();
				if (viewports && viewports.length > 0) {
					const viewport = viewports[0];
					const element = viewport.element;

					// 直接设置鼠标光标样式
					console.log("直接设置鼠标光标样式");
					element.style.cursor = "crosshair";

					// 延迟一小段时间，确保所有状态更新完成
					setTimeout(() => {
						// 触发鼠标移动事件来刷新光标
						const mouseMoveEvent = new MouseEvent("mousemove", {
							bubbles: true,
							cancelable: true,
							clientX: 100,
							clientY: 100
						});
						element.dispatchEvent(mouseMoveEvent);
						console.log("延迟鼠标移动事件已触发");
					}, 50); // 延迟50毫秒
				}
			}
		} catch (e) {
			console.log("强制刷新鼠标光标失败:", e);
		}
	} catch (error) {
		console.error("激活测量工具失败:", error);
	}
}

function updateToolBindings(window, zoom, pan, scroll, measure, measureType) {
	console.log("=== updateToolBindings 被调用 ===");
	console.log(
		"参数: window=",
		window,
		"zoom=",
		zoom,
		"pan=",
		pan,
		"scroll=",
		scroll,
		"measure=",
		measure,
		"measureType=",
		measureType
	);

	let bindings = [];

	// 完全禁用工具调窗功能，因为我们移除了工具调窗按钮
	toolGroup.setToolDisabled(WindowLevelTool.toolName);
	toolGroup.setToolPassive(WindowLevelTool.toolName);

	if (zoom == 0) {
		toolGroup.setToolDisabled(ZoomTool.toolName);
		console.log("缩放工具已禁用");
	} else {
		bindings = [];
		if (zoom & 1) {
			bindings.push({
				mouseButton: MouseBindings.Primary // Left Click
			});
			// 为触摸设备添加触摸绑定 - 使用cornerstone支持的触摸事件
			bindings.push({
				mouseButton: MouseBindings.Primary,
				modifierKey: KeyboardBindings.None
			});
			// 添加多点触摸绑定
			bindings.push({
				numTouchPoints: 2, // 双指触摸
				modifierKey: KeyboardBindings.None
			});
		}

		if (zoom & 2) {
			bindings.push({
				mouseButton: MouseBindings.Secondary // Right Click
			});
		}

		if (zoom & 4) {
			bindings.push({
				mouseButton: MouseBindings.Auxiliary // Middle Click
			});
		}

		console.log("激活缩放工具，绑定:", bindings);
		toolGroup.setToolDisabled(ZoomTool.toolName);
		toolGroup.setToolActive(ZoomTool.toolName, {
			bindings
		});

		// 检查工具状态
		const zoomOptions = toolGroup.getToolOptions(ZoomTool.toolName);
		console.log("缩放工具状态:", JSON.stringify(zoomOptions, null, 2));
	}

	if (pan == 0) {
		toolGroup.setToolDisabled(PanTool.toolName);
		console.log("移动工具已禁用");
	} else {
		bindings = [];
		if (pan & 1) {
			bindings.push({
				mouseButton: MouseBindings.Primary // Left Click
			});
			// 为触摸设备添加触摸绑定 - 使用cornerstone支持的触摸事件
			bindings.push({
				mouseButton: MouseBindings.Primary,
				modifierKey: KeyboardBindings.None
			});
			// 添加多点触摸绑定
			bindings.push({
				numTouchPoints: 1, // 单指触摸
				modifierKey: KeyboardBindings.None
			});
		}

		if (pan & 2) {
			bindings.push({
				mouseButton: MouseBindings.Secondary // Right Click
			});
		}

		if (pan & 4) {
			bindings.push({
				mouseButton: MouseBindings.Auxiliary // Middle Click
			});
		}

		console.log("激活移动工具，绑定:", bindings);
		toolGroup.setToolDisabled(PanTool.toolName);
		toolGroup.setToolActive(PanTool.toolName, {
			bindings
		});

		// 检查工具状态
		const panOptions = toolGroup.getToolOptions(PanTool.toolName);
		console.log("移动工具状态:", JSON.stringify(panOptions, null, 2));
	}

	if (scroll == 0) {
		toolGroup.setToolDisabled(StackScrollTool.toolName);
		toolGroup.setToolActive(StackScrollTool.toolName, {
			bindings: [{ mouseButton: MouseBindings.Wheel }]
		});
		console.log("滚动工具已禁用，但保持滚轮绑定");
	} else {
		bindings = [];
		bindings.push({
			mouseButton: MouseBindings.Wheel // Wheel Mouse
		});
		if (scroll & 1) {
			bindings.push({
				mouseButton: MouseBindings.Primary // Left Click
			});
			// 为触摸设备添加触摸绑定 - 使用cornerstone支持的触摸事件
			bindings.push({
				mouseButton: MouseBindings.Primary,
				modifierKey: KeyboardBindings.None
			});
			// 添加多点触摸绑定
			bindings.push({
				numTouchPoints: 1, // 单指触摸
				modifierKey: KeyboardBindings.None
			});
		}
		if (scroll & 2) {
			bindings.push({
				mouseButton: MouseBindings.Secondary // Right Click
			});
		}
		if (scroll & 4) {
			bindings.push({
				mouseButton: MouseBindings.Auxiliary // Middle Click
			});
		}

		console.log("激活滚动工具，绑定:", bindings);
		toolGroup.setToolDisabled(StackScrollTool.toolName);
		toolGroup.setToolActive(StackScrollTool.toolName, {
			bindings
		});

		// 检查工具状态
		const scrollOptions = toolGroup.getToolOptions(StackScrollTool.toolName);
		console.log("滚动工具状态:", JSON.stringify(scrollOptions, null, 2));
	}

	if (measure == 0) {
		// 测量工具未激活，设置测量工具为被动状态
		toolGroup.setToolPassive(selectedToolName);
	} else {
		bindings = [];
		if (measure & 1) {
			bindings.push({
				mouseButton: MouseBindings.Primary // Left Click
			});
		}

		if (measure & 2) {
			bindings.push({
				mouseButton: MouseBindings.Secondary // Right Click
			});
		}

		if (measure & 4) {
			bindings.push({
				mouseButton: MouseBindings.Auxiliary // Middle Click
			});
		}

		let type = measureType;
		if (type === "Label-L" || type === "Label-R") {
			type = LabelTool.toolName;
		}

		// 窗口调窗工具已被完全禁用，无需额外处理

		// 设置旧工具为被动状态
		toolGroup.setToolPassive(selectedToolName);

		// 激活新的测量工具
		toolGroup.setToolActive(type, {
			bindings
		});

		// 当测量工具激活时，确保基本工具不会干扰测量工具
		// 将基本工具设置为被动状态，但保持它们的绑定
		toolGroup.setToolPassive(ZoomTool.toolName);
		toolGroup.setToolPassive(PanTool.toolName);
		toolGroup.setToolPassive(StackScrollTool.toolName);

		console.log("测量工具激活，基本工具已设置为被动状态");

		if (measureType === "Label-L" || measureType === "Label-R") {
			const text = measureType.split("-")[1];
			toolGroup.setToolConfiguration(
				LabelTool.toolName,
				{
					getTextCallback: fn => {
						// console.log("getTextCallback", fn);
						return fn(text);
					}
					// changeTextCallback: (a, b, fn) => {
					// 	return fn(text);
					// }
				}
				// true
			);
		} else if (measureType === "Label") {
			// prompt('Enter your annotation:')
			toolGroup.setToolConfiguration(
				LabelTool.toolName,
				{
					getTextCallback: fn => {
						// console.log("getTextCallback", fn);
						return fn(prompt("Enter your annotation:"));
					}
					// changeTextCallback: (a, b, fn) => {
					// 	return fn(prompt("Enter your annotation:"));
					// }
				}
				// true
			);
		}

		selectedToolName = type;
	}
}

function removeAllMeasures() {
	// annotation.state.removeAllAnnotations();
	removeAllAnnotations();
}

function removeViewportMeasures(viewport, imageId) {
	//removeAnnotations
	const element = viewport.element;
	let annotations = [];
	const tools = measureTools.filter(
		tool =>
			tool.value !== WindowLevelTool.toolName && tool.value !== EraserTool.toolName
	);
	tools.forEach(tool => {
		let viewerTools = getAnnotations(tool.value, element);

		viewerTools = viewerTools?.filter(
			annotation => annotation.metadata.referencedImageId === imageId
		);
		annotations.push(...viewerTools);
	});

	console.log("removeViewportMeasures", viewport.id, imageId, annotations);
	annotations.forEach(annotation => {
		removeAnnotation(annotation.annotationUID);
	});
}

function setReferenceSource(viewportId) {
	// console.log("setReferenceSource", viewportId);
	const renderingEngine = getRenderingEngine(renderingEngineId2d);
	const viewport = renderingEngine.getViewport(viewportId);
	if (!viewport) {
		console.warn("setReferenceSource: viewport not found", viewportId);
		return;
	}

	const data = viewport.getImageData();
	if (!data) {
		console.warn("setReferenceSource: image data not found", viewportId);
		return;
	}

	// console.log("setReferenceSource data", data);

	// let viewports = renderingEngine.getViewports();
	// viewports = filterViewportsWithToolEnabled(
	// 	viewports,
	// 	ReferenceLinesTool.toolName
	// );
	// console.log(
	// 	"setReferenceSource viewports with tool enabled",
	// 	ReferenceLinesTool.toolName,
	// 	viewports
	// );

	const r = toolGroup.setToolConfiguration(ReferenceLinesTool.toolName, {
		sourceViewportId: viewportId,
		showFullDimension: true
	});

	// console.log("setReferenceSource state", r);

	// toolGroup.setToolEnabled(ReferenceLinesTool.toolName);
	// toolGroup.setToolDisabled(ReferenceLinesTool.toolName);
}

function setReferenceImages(imageIds) {
	// const hasTool = toolGroup.hasTool(OverlayGridTool.toolName);
	// if (!hasTool) {
	// 	toolGroup.addTool(OverlayGridTool.toolName, {
	// 		sourceImageIds: imageIds
	// 	});
	// } else {
	// 	const r = toolGroup.setToolConfiguration(OverlayGridTool.toolName, {
	// 		sourceImageIds: imageIds
	// 	});

	// 	// console.log("setReferenceImages state", r);
	// }
	// toolGroup.setToolDisabled(ReferenceLinesTool.toolName);

	const r = toolGroup.setToolConfiguration(OverlayGridTool.toolName, {
		sourceImageIds: imageIds
	});
	// console.log("setReferenceImages", r, imageIds);

	toolGroup.setToolEnabled(OverlayGridTool.toolName);
}

function getReferenceLines(viewportId) {
	const renderingEngine = getRenderingEngine(renderingEngineId2d);
	const viewport = renderingEngine.getViewport(viewportId);
	let viewerTools = getAnnotations(ReferenceLinesTool.toolName, viewport.element);

	return viewerTools;
}

function addImageSliceSync(viewportId) {
	const synchronizer = SynchronizerManager.getSynchronizer(imageSliceSync);
	if (synchronizer) {
		synchronizer.add({ renderingEngineId2d, viewportId });
	}
}

function removeImageSliceSync(viewportId) {
	const synchronizer = SynchronizerManager.getSynchronizer(imageSliceSync);
	if (synchronizer) {
		synchronizer.remove({ renderingEngineId2d, viewportId });
	}
}

function enableReferenceLines(e) {
	if (e === true) {
		toolGroup.setToolEnabled(ReferenceLinesTool.toolName);
	} else {
		toolGroup.setToolDisabled(ReferenceLinesTool.toolName);
	}
}

export {
	initTools,
	toolGroup,
	measureTools,
	setVieportToolStyles,
	activeMeasureTool,
	updateToolBindings,
	removeAllMeasures,
	removeViewportMeasures,
	setReferenceSource,
	setReferenceImages,
	getReferenceLines,
	addImageSliceSync,
	removeImageSliceSync,
	enableReferenceLines
};
